﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Logging;

namespace StyleMVVM.DependencyInjection.Conditions
{
	public class WhenAppSetting : IExportCondition
	{
		private static string supplemental = typeof(WhenAppSetting).FullName;
		private object settingValue;
		private string settingName;
		private bool cacheAnswer;
		private bool? answer;

		public WhenAppSetting(string settingName, object settingValue, bool cacheAnswer)
		{
			this.settingName = settingName;
			this.settingValue = settingValue;
			this.cacheAnswer = cacheAnswer;
		}

		public bool ConditionMeet(IDependencyInjectionContainer container,
		                          IInjectionContext injectionContext,
		                          IExportStrategy exportStrategy)
		{
			if (answer.HasValue)
			{
				return answer.Value;
			}

			string appSetting = ConfigurationManager.AppSettings[settingName];
			bool returnValue = false;

			if (appSetting != null)
			{
				if (settingValue == null)
				{
					return false;
				}

				if (appSetting.GetType() == settingValue.GetType())
				{
					returnValue = Equals(settingValue, appSetting);
				}

				try
				{
					returnValue = Equals(settingValue, Convert.ChangeType(appSetting, settingValue.GetType()));
				}
				catch (Exception exp)
				{
					Logger.Error(
						string.Format("Exception thrown while converting {0} to {1}", appSetting, settingValue.GetType().FullName),
						supplemental,
						exp);
				}
			}
			else if (settingValue == null)
			{
				returnValue = true;
			}

			if (cacheAnswer)
			{
				answer = returnValue;
			}

			return returnValue;
		}
	}
}